package com.gzz.config;

import com.gzz.pojo.TicketOrder;
import com.gzz.service.TicketOrderService;
import com.gzz.utils.RedisKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

	@Autowired
	TicketOrderService ticketOrderService;

	public RedisKeyExpirationListener(RedisMessageListenerContainer container) {
		super(container);
	}

	/**
	 * 针对redis数据失效事件，进行数据处理
	 * @param message
	 * @param pattern
	 */
	@Override
	public void onMessage(Message message, byte[] pattern) {
		String key=message.toString();//生效的key
		if (key!=null && key.startsWith(RedisKeyUtils.OrderId)){//从失效key中筛选代表订单失效的key
			//截取订单号，查询订单，如果是未支付状态则取消订单
			int st = key.lastIndexOf(RedisKeyUtils.OrderId);
			String orderNo = key.substring(st+7,st+15);
			Long id = Long.valueOf(orderNo);
			TicketOrder ticketOrder = ticketOrderService.getById(id);
			if(ticketOrder==null){
				throw new RuntimeException("试图查看超时订单时，订单号无效");
			}else{
				Integer status = ticketOrder.getStatus();
				if(status==0){
					ticketOrderService.delOrderTimeoutById(id);
					System.out.println("订单号为："+orderNo+"的订单超时未支付，取消订单");
				}

			}



		}
	}
}
